package com.equipment.system.web.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.equipment.system.entity.Equipment;
import com.equipment.system.service.EquipmentService;
import com.equipment.system.web.annotation.ApiDecrypt;
import com.equipment.system.web.annotation.ApiEncrypt;
import com.equipment.system.web.utils.RemoteClientIpUtils;
import com.equipment.system.web.utils.Rest;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备Controller
 * ${DESCRIPTION}
 *
 * @author 杨凯
 * @create 2018-03-20 8:52
 **/
@RestController
@RequestMapping("/equipment")
public class EquipmentController {

	private static final Logger LOGGER = LoggerFactory.getLogger(EquipmentController.class);

	@Autowired
	private EquipmentService equipmentService;


	@PostMapping("/register")
	@ApiDecrypt(decrypt = true)
	@ApiEncrypt(encode = true)
	@ApiOperation(value="设备激活码注册", notes="")
	public Rest equipmentRegister(HttpServletRequest request) {
		Rest.Builder rest = Rest.newBuilder();
		String remoteIP = RemoteClientIpUtils.getRemoteIP(request);
		System.out.println(remoteIP);
		try {
			String result = (String) request.getAttribute("value");
			Equipment equipment = JSON.parseObject(result, Equipment.class);
			EntityWrapper wrapper = new EntityWrapper<Equipment>();
			wrapper.eq("machine_code", equipment.getMachineCode());
			int count = equipmentService.selectCount(wrapper);
			if (count < 1) {
				//设备不存在
				return rest.status(501).build();
			}
			wrapper.eq("poll_code", equipment.getPollCode());
			count = equipmentService.selectCount(wrapper);
			if(count < 1){
				//激活码不正确
				return rest.status(502).build();
			}

			wrapper.eq("activated_state", 0);
			count = equipmentService.selectCount(wrapper);

			if(count < 1){
				//激活码不正确
				return rest.status(503).build();
			}
			Equipment updateEquipment = new Equipment();
			updateEquipment.setActivatedState(1);
			equipmentService.update(updateEquipment,wrapper);
			//否则激活成功
			rest.status(200);
		} catch (Exception e) {
			LOGGER.error("设备注册错误", e);
			rest.status(500);
		}
		return rest.build();
	}

	@ApiOperation(value="设备添加", notes="设备添加Api")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "city", value = "城市", required = true, dataType = "String"),
			@ApiImplicitParam(name = "province", value = "省份", required = true, dataType = "String"),
			@ApiImplicitParam(name = "version", value = "省份", required = true, dataType = "String"),
			@ApiImplicitParam(name = "contacts", value = "联系人", required = true, dataType = "String"),
			@ApiImplicitParam(name = "contactNumber", value = "联系电话", required = true, dataType = "String"),
			@ApiImplicitParam(name = "pollCode", value = "激活码", required = true, dataType = "String"),
			@ApiImplicitParam(name = "machineCode", value = "机器编码", required = true, dataType = "String"),
	})
	@ApiResponse(code = 200, message = "添加成功")
	@PostMapping(value = "/add")
	public Rest addEquipment(@RequestBody Equipment equipment) {
		Rest.Builder rest = Rest.newBuilder();
		try {
			equipmentService.insert(equipment);
			rest.status(200);
		} catch (Exception e) {
			LOGGER.error("添加设备异常", e);
			rest.status(500);
		}
		return rest.build();
	}


	@GetMapping("/list")
	public Map<String, Object> equipmentList(@RequestParam(defaultValue = "0") int start, @RequestParam(defaultValue = "10") int length, @RequestParam("province") String province) {
		Map<String, Object> map = new HashMap<>(3);
		Page page = new Page(start, length);
		Page<Equipment> paperPage = equipmentService.selectEquipmentList(page, province);
		List<Equipment> list = paperPage.getRecords();
		map.put("data", list);
		map.put("count", paperPage.getTotal());
		return map;
	}

	@DeleteMapping("/id")
	public Rest deleteEquipmentById(@RequestParam("id") Integer id) {
		Rest.Builder rest = Rest.newBuilder();
		equipmentService.deleteById(id);
		return rest.status(200).build();
	}
}
